<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>商家支付</title>
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"/>
    <meta http-equiv="Pragma" content="no-cache"/>
    <meta http-equiv="Expires" content="0"/>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../css/pay.css">
    <script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
    <script src="../js/jquery-3.3.1.min.js"></script>
</head>
<body>
<form>
    <input hidden name="deviceId" th:value="${deviceId}">
    <input hidden name="openId" th:value="${openId}">


    <div id="payBox">
        <div class="pay_title">
            <img src="../image/shangjia.png"/><br>
            <span th:text="${storeName}">上海根式科技</span>
        </div>
        <div class="pay_input">
            <div id="payInput">付款金额</div>
            <!--                <input type="number" id="payInput" name="payInput" placeholder="付款金额" maxlength="6" pattern="[0-9]" />-->
            <b>￥</b>
        </div>
        <div class="pay_price">
            <b>￥</b>
            <span class="price">0.00</span>
            <span class="discount_price"></span>
        </div>
    </div>
    <div id="couponBox">
        <ul>

        </ul>
        <!--            <p>暂无优惠券!</p>-->
    </div>
</form>

<!--    模拟数字键盘-->
<div id="keyboard">
    <table border="" cellspacing="" cellpadding="">
        <tr>
            <td><span>1</span></td>
            <td><span>2</span></td>
            <td><span>3</span></td>
            <td><span><img src="../image/tuige.png"></span></td>
        </tr>
        <tr>
            <td><span>4</span></td>
            <td><span>5</span></td>
            <td><span>6</span></td>
            <td rowspan="3"><span class="payment_but">立即支付</span></td>
        </tr>
        <tr>
            <td><span>7</span></td>
            <td><span>8</span></td>
            <td><span>9</span></td>
        </tr>
        <tr>
            <td><span>.</span></td>
            <td colspan="2"><span>0</span></td>
        </tr>
    </table>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        var formData = $('form').serializeArray(),
            tempObj = {},
            cardDetailId = '',
            inputVal = '',
            couponData = '',
            act_money = '',
            rate = '',
            discount_price = '';
        var ua = window.navigator.userAgent.toLowerCase();
        $.each(formData, function (i, obj) {
            tempObj[obj.name] = obj.value;
        });


        // 监听input
        function changeInput(Val) {
            inputVal = Val;
            act_money = Val;
            discount_price = Math.floor(inputVal * (1 - rate) * 100) / 100;//折扣价
            if (inputVal >= 1) {
                if ($('.couponCon').is('.selection')) {
                    $('.price').css({'text-decoration': 'line-through', 'color': '#ff6926'}).text(toDecimal2(inputVal));
                    $('.discount_price').show().text(toDecimal2(discount_price));
                    act_money = toDecimal2(discount_price);

                } else {
                    $('.price').css({'text-decoration': 'none', 'color': '#000'}).text(toDecimal2(inputVal));
                    $('.discount_price').hide();
                    cardDetailId = '';

                }
            } else {
                $('.price').css({'text-decoration': 'none', 'color': '#000'}).text(toDecimal2(inputVal));
                $('.discount_price').hide();
                act_money = toDecimal2(inputVal);
            }


        }

        // 选择优惠券
        $(document).on('click', '.couponCon', function () {
            cardDetailId = $(this).attr('cardDetailId');
            rate = $(this).find('.couponCon_left').attr('discount');
            inputVal = $('#payInput').text();
            discount_price = Math.floor(inputVal * (1 - rate) * 100) / 100;//折扣价

            if (inputVal >= 1) {
                if ($(this).is('.selection')) {
                    $(this).removeClass('selection');
                    $(this).find('.couponCon_but span').removeClass('select').text('立即使用');
                    $('.price').css({'text-decoration': 'none', 'color': '#000'}).text(toDecimal2(inputVal));
                    $('.discount_price').hide();
                    cardDetailId= '';
                } else {
                    $(this).addClass('selection');
                    $(this).siblings().removeClass('selection');
                    $(this).find('.couponCon_but span').addClass('select').text('已使用');
                    $(this).siblings().find('.couponCon_but span').removeClass('select').text('立即使用');

                    $('.price').css({'text-decoration': 'line-through', 'color': '#ff6926'}).text(toDecimal2(inputVal));
                    $('.discount_price').show().text(toDecimal2(discount_price));
                    act_money = toDecimal2(discount_price);

                }
            } else {
                if (inputVal == '付款金额') {
                    $('.price').css({'text-decoration': 'none', 'color': '#000'}).text('0.00');
                } else {
                    $('.price').css({'text-decoration': 'none', 'color': '#000'}).text(inputVal);
                    $('.discount_price').hide();
                    act_money = toDecimal2(inputVal);
                }
                cardDetailId= '';
            }
        });


        //制保留2位小数，如：2，会在2后面补上00.即2.00
        function toDecimal2(x) {
            var f = parseFloat(x);
            if (isNaN(f)) {
                return false;
            }
            var f = Math.round(x * 100) / 100;
            var s = f.toString();
            var rs = s.indexOf('.');
            if (rs < 0) {
                rs = s.length;
                s += '.';
            }
            while (s.length <= rs + 2) {
                s += '0';
            }
            return s;
        }


        // 模拟数字键盘开始
        var input = $('#payInput'); //金额显示框
        var li = $('#keyboard span'); //键盘按钮集合
        li.click(function () {
            var KeyHtml = $(this).text();
            var inputVal = input.text();
            if (!KeyHtml) { //判断是否为退格
                if (inputVal == '付款金额') {
                    input.text('付款金额');
                    changeInput(0.00);
                } else {
                    if (input.text().length == '1') {
                        input.text('付款金额');
                        changeInput(0.00);
                        $('.couponCon').removeClass('selection');
                        $('.couponCon').find('.couponCon_but span').removeClass('select').text('立即使用');
                    } else {
                        var val = inputVal.substring(0, inputVal.length - 1);
                        input.text(val);//删除最后一位
                        changeInput(val);
                    }

                }

            } else if (inputVal == '付款金额') {
                input.text(KeyHtml);
                changeInput(KeyHtml);
            } else if (inputVal.indexOf(".") != -1 && KeyHtml == '.') {
                input.text(inputVal);
                changeInput(inputVal);
            } else if (inputVal.indexOf('.') != -1 && inputVal.split('.')[1].length == 2) {
                input.text(inputVal);
                changeInput(inputVal);
            } else {
                input.text(inputVal + KeyHtml);
                changeInput(inputVal + KeyHtml);
            }
            if (KeyHtml == '立即支付') {
                input.text(inputVal);
                if (inputVal == '付款金额') {
                    changeInput(0.00);
                } else {
                    changeInput(inputVal);
                }
            }
        });
        // 模拟数字键盘结束


        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            $('.couponBox').show();
            $.ajax({
                type: 'post',
                url: '../wxpay/getCpnInfo',
                data: {
                    'deviceId': tempObj.deviceId,
                    'openId': tempObj.openId
                },
                success: function (resp) {
                    var res = JSON.parse(resp);
                    couponData = res.data.cardList;
                    if (res.code === 1) {
                        if (couponData.length) {
                            $('#couponBox').show();
                            for (var i = 0; i < couponData.length; i++) {
                                $('#couponBox ul').append('<li class="couponCon" cardDetailId="' + couponData[i].cardDetailId + '">' +
                                    '<div class="couponCon_left" discount="' + couponData[i].discount + '">' +
                                    '<h3>' + couponData[i].activityName + '</h3>' +
                                    '<span class="coupon">' + couponData[i].cardName + '</span>' +
                                    '</div>' +
                                    '<div class="couponCon_but">' +
                                    '<span>立即使用</span>' +
                                    '</div>' +
                                    '</li>');
                            }
                        } else {
                            act_money = inputVal;
                            $('#couponBox').hide();
                        }

                    } else {
                        alert(res.message);
                    }
                }
            });
        } else if (ua.match(/AlipayClient/i) == 'alipayclient') {
            $('#couponBox').hide();
        }

        var isclick = true;
        $('.payment_but').on('click', function () {
            if (isclick) {
                isclick = false;
                var formData = $('form').serializeArray(),
                    tempObj = {};
                var ua = window.navigator.userAgent.toLowerCase();
                $.each(formData, function (i, obj) {
                    tempObj[obj.name] = obj.value;
                });
                //判断是微信还是支付宝
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    //微信支付
                    $.ajax({
                        type: 'post',
                        url: '../wxpay/jsPay',
                        data: {
                            'deviceId': tempObj.deviceId,
                            'money': inputVal,
                            'openId': tempObj.openId,
                            'cpnId': cardDetailId,
                            'act_money': act_money
                        },
                        success: function (res) {
                            isclick=true;
                            var jsdata = res.data;
                            if (res.code == 1) {
                                function onBridgeReady() {
                                    WeixinJSBridge.invoke(
                                        'getBrandWCPayRequest', {
                                            "appId": jsdata.appId,     //公众号名称，由商户传入
                                            "timeStamp": jsdata.timeStamp, //时间戳，自1970年以来的秒数
                                            "nonceStr": jsdata.nonceStr, //随机串
                                            "package": jsdata.package,
                                            "signType": jsdata.signType, //微信签名方式：
                                            "paySign": jsdata.paySign //微信签名
                                        },
                                        function (res) {
                                            if (res.err_msg == "get_brand_wcpay_request:ok") {
                                                alert("支付成功!")
                                            } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                                                alert("用户已取消!")
                                            } else if (res.err_msg == "get_brand_wcpay_request:fail") {
                                                alert("支付失败!")
                                            }
                                        });
                                }

                                if (typeof WeixinJSBridge == "undefined") {
                                    if (document.addEventListener) {
                                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                                    } else if (document.attachEvent) {
                                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                                    }
                                } else {
                                    onBridgeReady();
                                }
                            } else {
                                alert(res.message);
                            }

                        }
                    });
                } else if (ua.match(/AlipayClient/i) == 'alipayclient') {
                    //是支付宝
                    $.ajax({
                        type: 'post',
                        url: '../alipay/jsPay',
                        data: {
                            'deviceId': tempObj.deviceId,
                            'money': inputVal
                        },
                        success: function (resp) {
                            isclick=true;
                            if (resp.code == 1) {
                                window.open(resp.data.qrCode);
                            } else {
                                alert(resp.message);
                            }
                        }
                    });
                } else {
                    alert("请用微信或支付宝扫码!!!");
                }
            }


        });
    })


</script>

</body>
</html>